package com.zeedev.flyingsaucer.beers.activities.login;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import com.zeedev.flyingsaucer.beers.activities.ActivitiesConstants;
import com.zeedev.flyingsaucer.beers.activities.storechooser.StoreChooser;
import com.zeedev.flyingsaucer.beers.activities.storechooser.StoreSpinner;
import com.zeedev.flyingsaucer.ufoclub.R;
import mobi.zeedev.flyingsaucer.common.CredentialsModule.interfaces.ICredentials;
import mobi.zeedev.flyingsaucer.common.DataModule.FlyingSaucerConv;
import roboguice.activity.RoboActivity;
import roboguice.inject.InjectView;

public class LoginActivity extends RoboActivity {

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Constants
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    private static final String LOGIN_STATE = "LOGIN_ACTIVITY_STATE";

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Injections (gui)
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    @InjectView(R.id.passwordEditText)
    EditText passwordEditText;

    @InjectView(R.id.rememberMeCheckBox)
    CheckBox rememberCheckBox;

    @InjectView(R.id.cardNumberEditText)
    EditText cardNumberEditText;

    @InjectView(R.id.checkbox_non_member)
    CheckBox checkNonMember;

    @InjectView(R.id.loginButton)
    Button loginButton;

    @InjectView(R.id.storeNumberSpinner2)
    StoreSpinner storeSpinner;

    @InjectView(R.id.checkbox_mou_member)
    CheckBox mouCheckBox;

    @InjectView(R.id.checkbox_autologon)
    CheckBox ufoAutoLoginCheckBox;

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Injections (data)
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    @Inject
    Provider<SimpleCursorAdapter> mAdapter;

    @Inject
    @Named("autoPreferenceCredentials")
    ICredentials credentials;

    @Inject
    LoginController controller;

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Menu
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_login_refresh: {
                storeSpinner.refreshStoresList();
                return true;
            }
        }
        return false;
    }

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Return Behaviour
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

/*    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //return super.onKeyDown(keyCode, event);
        if (keyCode == KeyEvent.KEYCODE_BACK) {

//			this.setResult(Activity.RESULT_CANCELED);
//			this.finish();
            startActivity(new Intent().setAction(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME));
            return true;
        } else {
            return false;
        }
    }*/

    public StoreSpinner getStoreSpinner() {
        return storeSpinner;
    }

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Callbacks
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    private OnClickListener loginClicked = new OnClickListener() {

        @Override
        public void onClick(View v) {

            //TODO move this to modified homescreen that just routes you to the alternate activities with the same buttons
            if (credentials.getUfoNonMember()) {
                Intent storeChooserIntent = new Intent(LoginActivity.this, StoreChooser.class);
                startActivityForResult(storeChooserIntent, 0);
            } else {
                if (credentials.isLoginAvailable()) {

                    controller.saveCredentials();

                    setResult(ActivitiesConstants.LOGIN_PRESSED);
                    finish();

                } else {
                    Toast.makeText(LoginActivity.this, "You must not leave any blanks empty.", Toast.LENGTH_SHORT).show();
                }
            }

        }

    };

    private OnCheckedChangeListener checkMouRememberListener = new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            credentials.setUfoMouMember(b);
        }
    };

    private OnCheckedChangeListener checkNonmemberListener = new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            credentials.setUfoNonMember(b);
            controller.setAsNonMember(b);

        }
    };

    private OnCheckedChangeListener rememberChecked = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            credentials.setUfoRemember(isChecked);
            controller.setRememberMe(isChecked);

        }

    };

    private OnCheckedChangeListener autoLoginChecked = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            credentials.setUfoAutoLogin(isChecked);


        }

    };

    private OnItemSelectedListener fieldChanged = new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            Cursor c = (Cursor) arg0.getItemAtPosition(arg2);
            Integer number = c.getInt(c.getColumnIndex(FlyingSaucerConv.Stores.NUMBER));
            if (number != null) {
                storeSpinner.setStoreNumberWeak(number.toString());
                credentials.setStoreNumber(number.toString());
//                controller.resetBeerRefreshDate();
            }

        }


        @Override
        public void onNothingSelected(AdapterView<?> arg0) {


        }

    };

    private TextWatcher fieldTextWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            //TODO????
//            app.setLastBeerLookup(null);
//            controller.resetBeerRefreshDate();

            credentials.setPassword(passwordEditText.getText().toString());
            credentials.setCardNumber(cardNumberEditText.getText().toString());
        }

    };

    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    // Activity Life-cycle
    //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.login);

        getInjector().injectMembers(storeSpinner);

        loadFromCredentials(credentials);

        cardNumberEditText.addTextChangedListener(fieldTextWatcher);
        passwordEditText.addTextChangedListener(fieldTextWatcher);
        storeSpinner.setOnItemSelectedListener(fieldChanged);

        checkNonMember.setOnCheckedChangeListener(checkNonmemberListener);
        rememberCheckBox.setOnCheckedChangeListener(rememberChecked);
        mouCheckBox.setOnCheckedChangeListener(checkMouRememberListener);
        ufoAutoLoginCheckBox.setOnCheckedChangeListener(autoLoginChecked);

        loginButton.setOnClickListener(loginClicked);

    }

    private void loadFromCredentials(ICredentials cred) {

        ufoAutoLoginCheckBox.setChecked(cred.getUfoAutoLogin());

        passwordEditText.setText(cred.getPassword());

        mouCheckBox.setChecked(cred.getUfoMouMember());

        rememberCheckBox.setChecked(cred.getUfoRemember());

        cardNumberEditText.setText(cred.getCardNumber());

        storeSpinner.changeSpinner(cred.getStoreNumber());

    }

    @Override
    protected void onPause() {
        super.onPause();

        controller.saveCredentials();

        //TODO ???
        //this may not be necessary because it should remember what was entered, though not forever
//        controller.saveCredentials();

//        if (!(this.loginState == LoginState.REFRESHING) && app.getCredentials().getUfoRemember()) {
//            doState(LoginState.SAVE_CREDENTIALS);
//        }

    }


}


